import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/message")
public class MessageWall extends HttpServlet {
    //有关json格式转换都会用到他
    ObjectMapper objectMapper = new ObjectMapper();
    //浏览器发出请求，从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //标识格式，不要让客户端去猜
        resp.setContentType("application/json; charset=utf8");
        //从数据库中拿出数据，转换成json写给客户端
        try {
            resp.getWriter().write(objectMapper.writeValueAsString(load()));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //浏览器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取json数据,转换成java对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //保存数据到数据库
        try {
            save(message);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //数据提交成功，打印日志
        System.out.println("数据提交成功：from:" + message.getFrom()
        + "to: " + message.getTo() + "message: " + message.getMessage());
    }

    //--------------------数据库操作------------------------
    //从数据库中取数据
    private List<Message> load() throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/messagewall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("1111");
        //2.建立连接
        Connection connection = (Connection) dataSource.getConnection();
        //3.构造sql
        String sql = "select * from message";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4.执行sql
        ResultSet resultSet = statement.executeQuery();
        //遍历结果集合
        List<Message> list = new ArrayList<>();
        while(resultSet.next()) {
            Message message = new Message();
            //resultSet.getString 是从表中获取列
            message.setFrom(resultSet.getString("from"));
            message.setTo(resultSet.getString("to"));
            message.setMessage(resultSet.getString("message"));
            list.add(message);
        }
        //5.关闭连接
        statement.close();
        connection.close();
        //返回数据
        return list;
    }

    //将数据存放到数据库
    private void save(Message message) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/messagewall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1111");
        //2.建立连接
        Connection connection = (Connection) dataSource.getConnection();
        //3.构造sql
        String sql = "insert into message values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        //statement.setString下标从1开始设置
        statement.setString(1, message.getFrom());
        statement.setString(2,message.getTo());
        statement.setString(3, message.getMessage());
        //4.执行sql
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);
        //5.关闭连接
        statement.close();
        connection.close();
    }
}
















